let wxapi = require("./base.js").wxapi;
let api = require("./config.js").api;
const urlencoded = 'application/x-www-form-urlencoded'
const json = 'application/json'

const method = {
  post: "POST",
  get: "GET"
}

function fetch({
  url,
  data = '',
  method = 'POST',
  inBody = true
}) {
  return new Promise((resole, reject) => {
    wxapi("getNetworkType")
      .then(res => {
        if (res.networkType == "none") {
          wx.showToast({
            title: '网络好像不太好哦，请稍候再试',
            icon: "none"
          })
        } else {
          wx.showLoading({
            title: '请求中',
          })
          let token = wx.getStorageSync('token')
          console.log(token)
          wxapi("request", {
            url: api.base_url + url,
            header: {
              //'Authorization': 'Bearer ' + wx.getStorageSync('token'),
              //'content-type': 'application/x-www-form-urlencoded' // 拼接到url 
              'content-type': inBody ? json : urlencoded, // 放在body中
              'Authorization': token ? token : '123'
            },
            data: data,
            method: method,
          }).then(res => {
            wx.hideLoading({})
            if (res.data.code == 401) {
              //认证失败，重新登录
              wx.showToast({
                title: '验证失败,自动重试',
                icon: "none"

              })
              wxapi("removeStorage", {
                key: "token"
              })
                .then(() => {
                  // 跳转至登陆页面
                  let jumpType = 0
                  console.log('tiaozhuan')
                  wx.navigateTo({
                    url: '/pages/login/login'
                  })
                })
                
            } else if (res.data.code == 200) {
              //成功
              //console.log(url)
              if(method != 'GET' && url != api.cinema_list){
                wx.showToast({
                  title: '操作成功',
                })
              }
              
              resole(res.data)
            } else {
              //失败
              wx.showToast({       
                title: res.data.message,
                icon: "none"
              })
              reject(res.data)
            }
          }).catch(res => {
            wx.hideLoading({})
            reject(res.data)
          })
            
        }
      })

  })
}

module.exports = {
  fetch,
  method
}